/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Principal;

/**
 * @author Tesla
 */
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import javax.imageio.ImageIO;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintServiceAttributeSet;
import javax.print.attribute.PrintServiceAttributeSet;
import javax.print.attribute.standard.PrinterName;

public class Ticket{
    static jcProperties editarpropiedades = new jcProperties();
    static Properties propiedades;
    static PrinterJob job = PrinterJob.getPrinterJob();
  //  static DocPrintJob job = service.createPrintJob();

    static PageFormat format = job.getPageFormat(null);
    static Paper paper = new Paper();
    static PrintService[] printServices;
    static PrintService printService;
    public static int size = 0;//0 = 80mm, 1 = 55mm
    static ArrayList<String> CabezaLineas = new ArrayList<>();
    public static ArrayList<String> subCabezaLineas = new ArrayList<>();
    public static ArrayList<String> importes = new ArrayList<>();
    public static ArrayList<String> nombres = new ArrayList<>();
    public static ArrayList<String> items = new ArrayList<>();
    static ArrayList<String> LineasPie = new ArrayList<>();
    static String pesoTotal;
    static String total;
    public static String tipopago="";
    static double recibido;
    static boolean impreso = false;
    public static String nombre="";
    public static float saldo =0.0f;
    static Number number = null;
    public static boolean credito= false;
    static NumberFormat fmt = NumberFormat.getInstance();
    static Printable imprimir;
    DecimalFormat df=new DecimalFormat("0.00");  
    public Ticket(){
        
        switch (size){
            case 0:
                imprimir =new Printable() {
            @Override
            public int print(Graphics pg, PageFormat pf, int pageNum)
                    throws PrinterException {
                if (pageNum > 0) {
                    return Printable.NO_SUCH_PAGE;
                }
                if(!impreso)
                    impreso=true;
                else
                try {
                    Graphics2D g2 = (Graphics2D) pg;
                    int x = (int) pf.getImageableX();
                    int y = (int) pf.getImageableY();
                    int posy = 55;//posicion desde donde empieza a imprimir
                    g2.setFont(new Font("CourierThai", Font.PLAIN, 8));
                    g2.translate(pf.getImageableX(), pf.getImageableY());
                    File img = new File("TESLAbem_logo_ticket.jpg");
                    BufferedImage in = ImageIO.read(img);
                    g2.drawImage(in, x, y, 200, 50, null);
                    int textHeight = g2.getFontMetrics().getHeight();
                    int stringLen;
                    for (String CabezaLinea : CabezaLineas) {
                        stringLen = (int) g2.getFontMetrics().getStringBounds(CabezaLinea, g2).getWidth(); //esto determina la longitud de la cadena
                        g2.drawString(CabezaLinea, 105 - stringLen / 2, posy); //esto la dibuja en medio
                        posy += textHeight;
                    }
                    for (String subCabezaLinea : subCabezaLineas) {
                        g2.drawString(subCabezaLinea, x, posy);
                        posy += textHeight;
                    }
                    if (!nombre.equals(""))
                    {
                        g2.drawString("Cliente: "+nombre, x, posy); 
                         posy+=textHeight;
                    }
                    if (!tipopago.equals(""))
                    {
                        g2.drawString("Pago Con: "+tipopago, x, posy); 
                         posy+=textHeight;
                    }
                    g2.drawLine(0, posy, 272, posy);
                    posy += textHeight;
                    g2.drawString("CANT      CODIGO      PRECIO U.", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds("IMPORTE", g2).getWidth();
                    g2.drawString("IMPORTE", 205 - stringLen, posy);
                    posy += 2;
                    g2.drawLine(0, posy, 272, posy);
                    posy += textHeight;
                    for (int i = 0; i < items.size(); i++) {
                        g2.drawString(nombres.get(i), x, posy);
                        posy += textHeight;
                        g2.drawString(items.get(i), x, posy);
                        stringLen = (int) g2.getFontMetrics().getStringBounds(importes.get(i), g2).getWidth();
                        g2.drawString(importes.get(i), 205 - stringLen, posy);
                        posy += textHeight;
                    }
                    posy -= 4;
                    g2.drawLine(0, posy, 272, posy);
                    posy += textHeight;
                    g2.drawString("PESO TOTAL:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds((pesoTotal + " gr"), g2).getWidth();
                    g2.drawString((pesoTotal + " gr"), 205 - stringLen, posy);
                    posy += 2 * textHeight;
                    String letras;
                    try {
                        number = fmt.parse(total);
                    } catch (ParseException ex) {
                    }
                    letras = NumberToLetterConverter.convertNumberToLetter(number.doubleValue()) + " 00/100M.N.";
                    g2.drawString("TOTAL:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds(total, g2).getWidth();
                    g2.drawString(total, 205 - stringLen, posy);
                    g2.drawString("$", 165, posy);
                    posy += textHeight;
                    ArrayList<String> precioletras = new ArrayList<>();
                    StringTokenizer tokens = new StringTokenizer(letras);
                    while (tokens.hasMoreTokens()) {
                        precioletras.add(tokens.nextToken());
                    }
                    int xletras = x;
                    for (int i = 0; i < precioletras.size(); i++) {
                        g2.drawString(precioletras.get(i), xletras, posy);
                        stringLen = (int) g2.getFontMetrics().getStringBounds(precioletras.get(i), g2).getWidth();
                        xletras += stringLen + 3;
                        if ((i % 3 == 0) && i > 0) {
                            xletras = x;
                            posy += textHeight;
                        }

                    }
                    posy += 2 * textHeight;
                    g2.drawString("RECIBIDO:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds(df.format(recibido), g2).getWidth();
                    g2.drawString(df.format(recibido), 205 - stringLen, posy);
                    g2.drawString("$", 165, posy);
                    posy += textHeight;
                    if (!credito){
                        //System.out.println("no hay credito");
                    g2.drawString("CAMBIO:", x, posy);
                    float camb = (float)recibido - number.floatValue();
                    if (camb<0)camb=0.00f;
                    String cambio = String.valueOf(camb) + "0";
                    stringLen = (int) g2.getFontMetrics().getStringBounds(cambio, g2).getWidth();
                    g2.drawString(cambio, 205 - stringLen, posy);
                    g2.drawString("$", 165, posy);
                    posy += 2 * textHeight;
                }
                    else{
                        System.out.println("si hay credito");
                        //credito = false;
                        g2.drawString("ADEUDO:", x, posy);
                    String cambio = String.valueOf(saldo) + "0";
                    stringLen = (int) g2.getFontMetrics().getStringBounds(cambio, g2).getWidth();
                    g2.drawString(cambio, 205 - stringLen, posy);
                    g2.drawString("$", 165, posy);
                    posy += 2 * textHeight;
                    stringLen = (int) g2.getFontMetrics().getStringBounds("Firma", g2).getWidth(); //esto determina la longitud de la cadena
                        g2.drawString("Firma", 105 - (stringLen/2), posy);//esto la dibuja en medio
                        posy += 30;
                        g2.drawLine(30, posy, 180, posy);
                        posy+=10;                    
                        stringLen = (int) g2.getFontMetrics().getStringBounds(nombre, g2).getWidth();
                        g2.drawString(nombre, 105 - (stringLen/2), posy); 
                       // System.out.println(nombre);
                        posy += 2*textHeight;
                    }
                    
                    for (String LineasPie1 : LineasPie) {
                        stringLen = (int) g2.getFontMetrics().getStringBounds(LineasPie1, g2).getWidth();
                        g2.drawString(LineasPie1, 105 - stringLen / 2, posy);
                        posy += textHeight;
                    }
paper.setSize(226, posy);
                } catch (IOException ex) {System.out.println("aca esta el error "+ex.getMessage());
                }
                return Printable.PAGE_EXISTS;
            }
        };
                break;
            case 1: 
                imprimir = new Printable() {
            @Override
            public int print(Graphics pg, PageFormat pf, int pageNum)
                    throws PrinterException {
                if (pageNum > 0) {
                    return Printable.NO_SUCH_PAGE;
                }
                if(!impreso)
                    impreso=true;
                else
                try {
                    Graphics2D g2 = (Graphics2D) pg;
                    int x = (int) pf.getImageableX();
                    int y = (int) pf.getImageableY();
                    int posy = 15;//posicion desde donde empieza a imprimir
                    g2.setFont(new Font("CourierThai", Font.PLAIN, 8));
                    g2.translate(pf.getImageableX(), pf.getImageableY());
                    //File img = new File("TESLAbem_logo_ticket.jpg");
                    //BufferedImage in = ImageIO.read(img);
                   // g2.drawImage(in, x, y, 200, 50, null);
                    int textHeight = g2.getFontMetrics().getHeight();
                    int stringLen;
                    for (String CabezaLinea : CabezaLineas) {
                        stringLen = (int) g2.getFontMetrics().getStringBounds(CabezaLinea, g2).getWidth(); //esto determina la longitud de la cadena
                        g2.drawString(CabezaLinea, 69 - stringLen / 2, posy); //esto la dibuja en medio
                        posy += textHeight;
                    }
                    for (String subCabezaLinea : subCabezaLineas) {
                        g2.drawString(subCabezaLinea, x, posy);
                        posy += textHeight;
                    }
                    if (!nombre.equals(""))
                    {
                        g2.drawString("Cliente: "+nombre, x, posy); 
                         posy+=textHeight;
                    }
                    if (!tipopago.equals(""))
                    {
                        g2.drawString("Pago Con: "+tipopago, x, posy); 
                         posy+=textHeight;
                    }
                    g2.drawLine(0, posy, 149, posy);
                    posy += textHeight;
                    g2.drawString("CANT  CODIGO  PRECIO U.", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds("IMPORTE", g2).getWidth();
                    g2.drawString("IMPORTE", 148 - stringLen, posy);
                    posy += 2;
                    g2.drawLine(0, posy, 149, posy);
                    posy += textHeight;
                    for (int i = 0; i < items.size(); i++) {
                        g2.drawString(nombres.get(i), x, posy);
                        posy += textHeight;
                        g2.drawString(items.get(i), x, posy);
                        stringLen = (int) g2.getFontMetrics().getStringBounds(importes.get(i), g2).getWidth();
                        g2.drawString(importes.get(i), 148 - stringLen, posy);
                        posy += textHeight;
                    }
                    posy -= 4;
                    g2.drawLine(0, posy, 149, posy);
                    posy += textHeight;
                    g2.drawString("PESO TOTAL:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds((pesoTotal + " gr"), g2).getWidth();
                    g2.drawString((pesoTotal + " gr"), 148 - stringLen, posy);
                    posy += 2 * textHeight;
                    String letras;
                    try {
                        number = fmt.parse(total);
                    } catch (ParseException ex) {
                    }
                    letras = NumberToLetterConverter.convertNumberToLetter(number.doubleValue()) + " 00/100M.N.";
                    g2.drawString("TOTAL:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds(total, g2).getWidth();
                    g2.drawString(total, 148 - stringLen, posy);
                    g2.drawString("$", 105, posy);
                    posy += textHeight;
                    ArrayList<String> precioletras = new ArrayList<>();
                    StringTokenizer tokens = new StringTokenizer(letras);
                    while (tokens.hasMoreTokens()) {
                        precioletras.add(tokens.nextToken());
                    }
                    int xletras = x;
                    for (int i = 0; i < precioletras.size(); i++) {
                        g2.drawString(precioletras.get(i), xletras, posy);
                        stringLen = (int) g2.getFontMetrics().getStringBounds(precioletras.get(i), g2).getWidth();
                        xletras += stringLen + 3;
                        if ((i % 2 == 0) && i > 0) {
                            xletras = x;
                            posy += textHeight;
                        }

                    }
                    posy += 2 * textHeight;
                    g2.drawString("RECIBIDO:", x, posy);
                    stringLen = (int) g2.getFontMetrics().getStringBounds(df.format(recibido), g2).getWidth();
                    g2.drawString(df.format(recibido), 148 - stringLen, posy);
                    g2.drawString("$", 105, posy);
                    posy += textHeight;
                    if (!credito){
                      //  System.out.println("no hay credito");
                    g2.drawString("CAMBIO:", x, posy);
                    float camb = (float)recibido - number.floatValue();
                    if (camb<0)camb=0.00f;
                    String cambio = String.valueOf(camb) + "0";
                    stringLen = (int) g2.getFontMetrics().getStringBounds(cambio, g2).getWidth();
                    g2.drawString(cambio, 148 - stringLen, posy);
                    g2.drawString("$", 105, posy);
                    posy += 2 * textHeight;
                }
                    else{
                       // System.out.println("si hay credito");
                        //credito = false;
                        g2.drawString("ADEUDO:", x, posy);
                    String cambio = String.valueOf(saldo) + "0";
                    stringLen = (int) g2.getFontMetrics().getStringBounds(cambio, g2).getWidth();
                    g2.drawString(cambio, 148 - stringLen, posy);
                    g2.drawString("$", 105, posy);
                    posy += 2 * textHeight;
                    stringLen = (int) g2.getFontMetrics().getStringBounds("Firma", g2).getWidth(); //esto determina la longitud de la cadena
                        g2.drawString("Firma", 68 - (stringLen/2), posy);//esto la dibuja en medio
                        posy += 30;
                        g2.drawLine(20, posy, 125, posy);
                        posy+=10;                    
                        stringLen = (int) g2.getFontMetrics().getStringBounds(nombre, g2).getWidth();
                        g2.drawString(nombre, 68 - (stringLen/2), posy); 
                       // System.out.println(nombre);
                        posy += 2*textHeight;
                    }
                    
                    for (String LineasPie1 : LineasPie) {
                        stringLen = (int) g2.getFontMetrics().getStringBounds(LineasPie1, g2).getWidth();
                        g2.drawString(LineasPie1, 68 - stringLen / 2, posy);
                        posy += textHeight;
                    }
paper.setSize(141, posy);
                } catch (NumberFormatException ex) {System.out.println("aca esta el error "+ex.getMessage());
                }
                return Printable.PAGE_EXISTS;
            }
        };
                break;
        }
                
        CabezaLineas.clear();
        LineasPie.clear();
        try {
            PreparedStatement ps = local_connection.cn.prepareStatement("select linea from lineasticket where sucursal = ? and cabeza = 1");
            ps.setInt(1, VentanaPrincipal.sucursal);
            ResultSet rs= ps.executeQuery();
            while(rs.next()){
                AddCabecera(rs.getString(1));
            }
             ps = local_connection.cn.prepareStatement("select linea from lineasticket where sucursal = ? and cabeza = 0");
             ps.setInt(1, VentanaPrincipal.sucursal);
             rs= ps.executeQuery();
            while(rs.next()){
                AddPieLinea(rs.getString(1));
            }
        } catch (SQLException ex) {
            VentanaPrincipal.logger.log(Level.SEVERE, null, ex);
        }
        /*AddCabecera("REPECO");
        AddCabecera("Michel Morales Molina");
        AddCabecera("RFC MOMM8804289V1");
        AddCabecera("11 PONIENTE 113 COLONIA CENTRO");
        AddCabecera("PUEBLA, PUE. TEL.(222)232-1705");*/
        AddCabecera(DarEspacio());
        /*AddPieLinea("¡GRACIAS POR TU COMPRA!");
        AddPieLinea("www.teslabem.com");*/
         propiedades = new Properties();
        propiedades = editarpropiedades.getProperties();
        PrintServiceAttributeSet printServiceAttributeSet = new HashPrintServiceAttributeSet();
        printServiceAttributeSet.add(new PrinterName(propiedades.getProperty("impresoraTicket"), null));
        printServices = PrintServiceLookup.lookupPrintServices(null, printServiceAttributeSet);
        //Los bordes y el tamaño del papel
       paper.setImageableArea(8, 0.0, 227, 1000);
        format.setPaper(paper);
        //imprimir ticket
          try {
            printService = printServices[0];
            job.setPrintService(printService);   // intentare imprimir con la impresora de tickets
        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Error: No se encontro la impresora '" + propiedades.getProperty("impresoraTicket") + "', usare la impresora por default");
        } catch (PrinterException exception) {
            System.err.println("Erro de impresion: " + exception);
        }
         job.setPrintable(imprimir,format);
                 
    }

    public static void AddCabecera(String line) {
        CabezaLineas.add(line);
    }

    public static void AddSubCabecera(String line) {
        subCabezaLineas.add(line);
    }

    public static void AddNombre(String line) {
        nombres.add(line);
    }

    public static void AddImporte(String line) {
        importes.add(line);
    }


    public static void AddItem(String cantidad, String codigo, String precio) {
        switch (size){
            case 0: items.add(cantidad + "             " + codigo + "             " + precio); break;
            case 1: items.add(cantidad + "         " + codigo + "          " + precio); break;
        }
        
    }

    public static void setPeso(String p) {
        pesoTotal = p;
    }

    public static void setRecibido(String p) {
        recibido = Double.parseDouble(p);
    }

    public static void setTotal(String p) {
        total = p;
    }

    public static void AddPieLinea(String line) {
        LineasPie.add(line);
    }

    public static String DarEspacio() {
        return "\n";
    }

    /**
     *
     */
    
   

       
       
       
    
   
}
